<template>
      <div class="content" v-loading="loading">
          <div class="left-box">
              <div style="margin:20px 0px">
                 <el-button type="primary" size="small"  @click="newDilog" plain>开启新对话</el-button>
              </div>
              <el-table
              ref="myTable"
              :data="hisData"
              highlight-current-row
              max-height="500px"
              @current-change="handleCurrentChange"
              >
              <el-table-column
                prop="date"
                label="历史列表"
                >
                <template #default="{ row }">
                  <div style="display:flex;align-items:center;justify-content:space-between">
                    <div>
                      {{formatDate(row.createdAt)}}
                    </div>
                    <div>
                       <!-- <el-button type="text" icon="el-icon-delete" circle style="color:#F56C6C" @click.stop="deleteData(row.id,row.status)" v-if="row.status=='PENDING'"></el-button> -->
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="right-box" >
            <div>
                    <div class="select-template">
                        <div class="select-header">
                          <div class="select-header-title">输入需求</div>
                        </div>
                         <!-- <div style="min-width:500px;">
                            <el-input type="textarea"  rows="10" placeholder="请输入你的需求" v-model="query" :readonly="hisFlag"></el-input>
                          </div> -->
                        <div style="">
                          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm" inline size="small">
                              <el-form-item label="项目数" prop="pro_num">
                                <el-input v-model.number="ruleForm.pro_num" :disabled="hisFlag"></el-input>
                              </el-form-item>
                              <el-form-item label="金额" prop="money">
                                <el-input v-model="ruleForm.money" :disabled="hisFlag"></el-input>
                              </el-form-item>
                              <el-form-item label="审计方法名称" prop="name">
                                <el-input v-model="ruleForm.name" :disabled="hisFlag"></el-input>
                              </el-form-item>
                              <el-form-item label="项目名称" prop="pro_name">
                                <el-input v-model="ruleForm.pro_name" :disabled="hisFlag"></el-input>
                              </el-form-item>
                              <el-form-item label="被审计单位名称" prop="sjed_name">
                                <el-input v-model="ruleForm.sjed_name" :disabled="hisFlag"></el-input>
                              </el-form-item>
                              <el-form-item label="数据来源" prop="datafrom">
                                <el-input v-model="ruleForm.datafrom" :disabled="hisFlag"></el-input>
                              </el-form-item>
                              
                            </el-form>
                        </div>
                      </div>
                      <div style="margin:20px 0px">
                            <el-button type="" size="small" @click="reset" :disabled="hisFlag" v-if="!hisFlag">重置</el-button>
                            <el-button type="primary" size="small" @click="onSubmit" :disabled="hisFlag" v-if="!hisFlag">自动生成</el-button>
                            <el-alert title="自动生成任务已完成" type="success" effect="dark" :closable="false" v-if="hisFlag && state=='COMPLETED'"></el-alert>
                            <el-alert title="自动生成任务等待处理" type="info" effect="dark" :closable="false" v-if="hisFlag && state=='PENDING'"></el-alert>
                            <el-alert title="自动生成任务处理中"  type="warning" effect="dark" :closable="false" v-if="hisFlag && state=='PROCESSING'"></el-alert>
                            <el-alert title="自动生成任务已失败" type="error" effect="dark" :closable="false" v-if="hisFlag && state=='FAILED'"></el-alert>
                      </div>
                      <div class="select-header" style="margin-top:20px">
                          <div class="select-header-title">生成结果</div>
                        </div>
                      <div  class="code" style="max-width:800px;">
                        <vue-markdown :source="sqlContent"></vue-markdown>
                      </div>
                      <div>
                        <el-button  size="small" @click="copyClick(sqlContent)"  v-if="hisFlag && sqlContent">复制全文</el-button>
                        <el-button  size="small" type="danger"   @click="deleteData()" v-if="state=='PENDING'">取消任务排队</el-button>
                        <el-button type="success" :disabled="bookid==''" style="width:360px;height:50px"  @click="downLoad">立即下载</el-button>
                      </div>
                  </div>
          </div>
      </div>
</template>
<script>
import VueMarkdown from 'vue-markdown';
import { formatDateTime } from '@/tools/index'
export default {
  name: 'PickupForm',  
  data(){
    return{
      loading:false,
      query:'',
      hisData:[],
      sqlContent:'',
      hisFlag:false,
      type:'PICKUP_FORM',
      state:'',
      timeoutId:null,
      delId:'',
      ruleForm: {
          pro_num: '',
          money: '',
          name: '',
          pro_name: '',
          sjed_name: '',
          datafrom:'',
      },
      rules: {
        pro_num: [
            { required: true, message: '请输入项目数', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                if (!value) {
                  return callback();
                }
                if (!/^[0-9]+$/.test(value)) {
                  callback(new Error('项目数必须为数字值'));
                } else {
                  callback();
                }
              },
              trigger: 'blur'
            }
          ],
          money: [
            { required: true, message: '请输入金额', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                if (!value) {
                  return callback();
                }
                if (!/^(\d+|\d+.\d{1,2})$/.test(value)) {
                  callback(new Error('请输入正确的金额格式'));
                } else {
                  callback();
                }
              },
              trigger: 'blur'
            }
          ],
          name: [
            { required: true, message: '请输入审计方法名称', trigger: 'blur' },
            { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
          ],
          pro_name: [
            { required: true, message: '请输入项目名称', trigger: 'blur' },
            { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
          ],
          sjed_name: [
            { required: true, message: '请输入被审计单位名称', trigger: 'blur' },
            { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
          ],
          datafrom: [
            { required: true, message: '请输入数据来源', trigger: 'blur' },
            { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
          ],
      }
    }
  },
  components: {
    VueMarkdown
  },
  computed: {
    compiledMarkdown() {
      return marked(this.sqlContent, { sanitize: true }); // 使用sanitize来避免XSS攻击
    }
  },
  created(){
    this.getHisData(false);
  },
  methods:{
    reset(){
      this.ruleForm={
          pro_num: '',
          money: '',
          name: '',
          pro_name: '',
          sjed_name: '',
          datafrom:'',
      }
    },
    newDilog(){
      clearTimeout(this.timeoutId);
      this.ruleForm={
          pro_num: '',
          money: '',
          name: '',
          pro_name: '',
          sjed_name: '',
          datafrom:'',
      },
      this.$refs.myTable.setCurrentRow()
      this.hisFlag=false;
      this.sqlContent='';
      
    },
    formatDate(time){
      console.log(99,time);
      return formatDateTime(time);
    },
    deleteData(){
      this.$confirm('取消任务排队将无法恢复，确认取消？').then(_ => {
          if(this.state!="PENDING"){
            this.$message.warning('当前任务状态已发生变更');
          }else{
            this.$axios.delete('/api/services/hzsfjtai/task/delete?id='+this.delId, {}).then(res => {
            if (res.data.code === 200) {
              this.$message.success('取消成功');
              this.getHisData(false);
            } else {
              this.$message(res.data.message)
            }
          }).catch(err => {
            this.$message.error(err)
          })
          }
      }).catch(_ => {});
    },
    handleCurrentChange(val) {
      if(val){
        clearTimeout(this.timeoutId);
        this.hisFlag=true;
        this.$axios.get('/api/services/hzsfjtai/task/getDesc?id='+val.id, {}).then(res => {
          if (res.data.code === 200) {
            this.delId=res.data.data.id;
            this.sqlContent =res.data.data.taskResponseData;
            this.state=res.data.data.status;
            this.ruleForm =JSON.parse(res.data.data.taskData);
            this.bookid =res.data.data.taskResponseData? JSON.parse(res.data.data.taskResponseData).id:'';
            let _this=this;
            if(_this.state!="COMPLETED"  &&  _this.state !="TIMEOUT"  &&  _this.state !="FAILED"){
             _this.timeoutId =   setTimeout(() => {
                    _this.handleCurrentChange(val); // 递归调用
                }, 3000);
            }else{
              val.status=_this.state
            }
          } else {
            this.$message(res.data.msg)
          }
        }).catch(err => {
          this.$message.error(err)
        })
      }
      
    },
    //获取历史数据
    getHisData(checkFlag){
      this.$axios.get('/api/services/hzsfjtai/task/getList?taskType='+this.type, {}).then(res => {
        if (res.data.code === 200) {
          this.hisData=res.data.data;
          if(checkFlag){
            this.$nextTick(()=>{
              this.$refs.myTable.setCurrentRow(this.hisData[0])
              this.loading=false
            })
          }
        } else {
          this.$message(res.data.msg)
        }
      }).catch(err => {
        this.$message.error(err)
      })
    },
    onSubmit() {
      this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            this.hisFlag=true
            this.loading=true
            this.$axios.post('/api/services/hzsfjtai/llm/pickupForm', this.ruleForm).then(res => {
                if (res.data.code === 200) {
                  this.getHisData(true);
                } else {
                  this.hisFlag=false
                  this.$message(res.data.msg)
                }

              }).catch(err => {
                this.$message.error(err)
              })
          } else {
            this.$message.warning('请填写完整信息');
            return false;
          }
      });
    },
    downLoad(){
      window.location.href="/api/services/hzsfjtai/file/downloadFile/"+this.bookid
    },
    copyClick(text) {
        this.$copyText(text).then(() => {
            this.$message.success('全文已复制');
        }).catch(() => {
            this.$message.warning('复制失败');
        });
    },
    exit(){
      this.$router.push({ path: '/dashboard' })
    },
  },
  mounted() {

  }
}
</script>
<style scoped lang="less" >
/deep/ .el-table .el-table__row:hover {
  cursor: pointer; /* 这里可以更改为其他的光标样式，比如 'crosshair', 'help', 'move', 'not-allowed' 等 */
}
</style>

